package top.fengleifeng.question;

import top.fengleifeng.util.Constants;

import javax.xml.stream.events.Characters;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * @program: leetcode-test
 * @description:
 * @author: fengleifeng
 * @create: 2020-10-19 16:23
 **/
public class Y剑指Offer38字符串的排列 {

    class Solution {
        public String[] permutation(String s) {
            char[] charArr = s.toCharArray();
            Arrays.sort(charArr);
            boolean[] used = new boolean[charArr.length];
            List<String> lists = new LinkedList<>();
            iterator(charArr, used, lists, new StringBuilder());
            String[] strings = new String[lists.size()];
            for (int i = 0; i < lists.size(); i++) {
                strings[i] = lists.get(i);
            }
            return strings;
        }

        private void iterator(char[] charArr, boolean[] used, List<String> lists, StringBuilder s) {
            if (s.length() == charArr.length) {
                lists.add(new String(s));
            }
            for (int i = 0; i < charArr.length; i++) {
                if (used[i]) {
                    continue;
                }
                if (i > 0 && charArr[i] == charArr[i - 1] && !used[i - 1]) {
                    continue;
                }
                used[i] = true;
                s.append(charArr[i]);
                iterator(charArr, used, lists, s);
                s.deleteCharAt(s.length() - 1);
                used[i] = false;
            }
        }
    }

    public static void main(String[] args) {
        String[] permutation = new Y剑指Offer38字符串的排列().new Solution().permutation("1233");
        Constants.printArr(permutation);
    }
}
